/**   
 * @Title: ChaseRecordAct.java 
 * @Package: com.esun.rabbit2.viewer.mainact.mylotteryact.chaserecord 
 * @Description: 大乐透追号记录列表Activity) 
 * @Author: Billy qigs@500wan.com   
 * @Date: 2011-7-20 下午12:26:10  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.mylotteryact.trackingrecord;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.TrackingRecordInfo;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.trackingrecord.TrackingRecordCommunicater;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView.OnRefreshListener;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: ChaseRecordAct
 * @Description: 大乐透追号记录列表Activity)
 * @Author: Billy qigs@500wan.com
 * @Date: 2011-7-20 下午12:26:10
 */
public class TrackingRecordDaLeTouAct extends Activity implements OnScrollListener, OnItemClickListener, OnRefreshListener {

	private PullToRefreshListView lvDaLeTouTrackingRecord;
	private TrackingRecrodAdapter adapter;
	private LinearLayout linearFooter;
	private LinearLayout linearNoMore;
	private LinearLayout linearBottom;
	private ProgressDialog progressDialog;
	private ArrayList<Hashtable<String, String>> alItem;
	public static Handler trackingRecordHandler;
	private LinearLayout linearNoRecord;
	private TrackingRecordCommunicater trackingRecordCommunicater;

	private String serverMessage;

	private boolean isRunning = false;
	private boolean isRefreshOrBottom = true;
	private boolean isNoMoreRecord;
	private boolean isShow = true;
	private boolean isBottomChanged = true;

	private static final int GET_TRACKINGRECORD_SUCCEED = 10001;
	private static final int GET_TRACKINGRECORD_FAILED = 10002;
	private int pageno = 1;
	private final int FOOTER_VIEW_TAG = 10000;
	private final int FOOTER_VIEW_TAG2 = 20000;
	private final int FOOTER_VIEW_TAG3 = 30000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trackingrecord_daletou_act);

		initUI();
		initHandler();
	}

	public void initUI() {

		progressDialog = ViewerUtil.showProgressDialog(TrackingRecordDaLeTouAct.this, getResources().getString(R.string.loading_text));
		progressDialog.show();

		linearNoRecord = (LinearLayout) findViewById(R.id.trackingrecord_daletouact_linear_noRecord);

		lvDaLeTouTrackingRecord = (PullToRefreshListView) findViewById(R.id.trackingrecord_listview_daLeTouRecord);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
		linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
		linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_bottom_view, null);
		linearFooter.setTag(FOOTER_VIEW_TAG);
		linearNoMore.setTag(FOOTER_VIEW_TAG2);
		linearBottom.setTag(FOOTER_VIEW_TAG3);
		alItem = new ArrayList<Hashtable<String, String>>();
		adapter = new TrackingRecrodAdapter(this, alItem);

		lvDaLeTouTrackingRecord.addFooterView(linearFooter);
		lvDaLeTouTrackingRecord.setAdapter(adapter);
		lvDaLeTouTrackingRecord.removeFooterView(linearFooter);
		lvDaLeTouTrackingRecord.setOnItemClickListener(this);
		lvDaLeTouTrackingRecord.setOnRefreshListener(this);
		lvDaLeTouTrackingRecord.setOnScrollListener(this);

		// lvDaLeTouTrackingRecord.onRefresh();
	}

	/* 通信线程 */
	public void getTrackingRecordThread() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				trackingRecordCommunicater = new TrackingRecordCommunicater();
				Message msg;
				try {
					// 2012-03-01 modified kuroky
					boolean isSucceed = trackingRecordCommunicater.isGetTrackingRecord(Config.DALETOU, String.valueOf(pageno), Config.NUM_1);
					// 2012-03-01 modified kuroky

					serverMessage = trackingRecordCommunicater.getServerMsg();
					EDebug.o(this, trackingRecordCommunicater.getServerMsg());
					if (isSucceed) {
						msg = trackingRecordHandler.obtainMessage(GET_TRACKINGRECORD_SUCCEED, null);
						trackingRecordHandler.sendMessage(msg);
					} else {
						msg = trackingRecordHandler.obtainMessage(GET_TRACKINGRECORD_FAILED, null);
						trackingRecordHandler.sendMessage(msg);
					}
				} catch (Exception e) {
					msg = trackingRecordHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					trackingRecordHandler.sendMessage(msg);
				}
			}

		}.start();
	}

	/* 消息处理 */
	public void initHandler() {
		trackingRecordHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				lvDaLeTouTrackingRecord.removeFooterView(linearBottom);
				switch (msg.what) {

				case GET_TRACKINGRECORD_SUCCEED:

					pageno++;
					infoHandling(trackingRecordCommunicater.updataTrackingRecordInfo());
					EDebug.o(this, "通讯成功！" + pageno);
					if (trackingRecordCommunicater.getListResult().size() < 10) {
						isNoMoreRecord = false;
						lvDaLeTouTrackingRecord.addFooterView(linearNoMore);
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case GET_TRACKINGRECORD_FAILED:

					EDebug.o(this, "通讯失败！");
					isBottomChanged = false;
					// 无更多记录
					if (trackingRecordCommunicater.getState() == 202 || trackingRecordCommunicater.getState() == 101) {
						isNoMoreRecord = false;
						if (pageno == 1) {
							// alItem.clear();
							linearNoRecord.setVisibility(View.VISIBLE);
						} else {
							lvDaLeTouTrackingRecord.addFooterView(linearNoMore);
						}
					} else {
						// 通讯失败
						showNoMoreRecordDialog(serverMessage);
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.CONNECTION_FAIL:

					EDebug.o(this, "连接失败！");
					isBottomChanged = false;
					showNoMoreRecordDialog(Language.STR_CONNECTIONFAIL);
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.DO_REFRESH:

					if (!isRunning) {
						lvDaLeTouTrackingRecord.prepareForRefresh();
						lvDaLeTouTrackingRecord.onRefresh();
						progressDialog.show();
					}
					TrackingRecordActGroup.isCanClick = true;
					break;

				default:
					break;
				}
			}
		};
	}

	private void endProcess() {
		if (progressDialog != null) {
			progressDialog.cancel();
		}
		isRunning = false;
		if (isRefreshOrBottom) {
			lvDaLeTouTrackingRecord.onRefreshComplete();
		} else {
			lvDaLeTouTrackingRecord.removeFooterView(linearFooter);
		}
	}

	/* 追号记录点击事件* */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg1.getTag() != null
				&& (Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG || Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG2 || Integer.parseInt(String.valueOf(arg1
						.getTag())) == FOOTER_VIEW_TAG3)) {
			return;
		} else {
			// 2012-03-02 modified by kuroky
			// 判断是否能够点击进入详情
			String lotid = alItem.get(arg2 - 1).get(Key.KEY_LOTID);
			if (!lotid.equals(Config.SHUANGSEQIU) && !lotid.equals(Config.DALETOU)) {
				Toast.makeText(TrackingRecordDaLeTouAct.this, Language.POPLOTTERYTIP_LOTID_NOT_SUPPORTED, Toast.LENGTH_SHORT).show();
			} else {
				Bundle bundle = new Bundle();
				bundle.putString(Key.KEY_LOTID, alItem.get(arg2 - 1).get(Key.KEY_LOTID));
				bundle.putString(Key.KEY_PID, alItem.get(arg2 - 1).get(Key.KEY_PID));
				Intent intent = new Intent();
				intent.setClass(TrackingRecordDaLeTouAct.this, TrackingRecordDetailAct.class);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		}
	}

	/* 滑动到底事件* */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
			if (isNoMoreRecord) {
				if (!isRunning && isBottomChanged) {
					EDebug.o(this, "到底加载...");
					isRunning = true;
					lvDaLeTouTrackingRecord.addFooterView(linearFooter);
					isRefreshOrBottom = false;
					getTrackingRecordThread();
				}
			}
		} else {
			isBottomChanged = true;
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
	}

	/* 刷新* */
	@Override
	public void onRefresh() {
		if (!isRunning) {
			EDebug.o(this, "刷新...");
			EDebug.o(this, isRunning);
			linearNoRecord.setVisibility(View.GONE);
			if (lvDaLeTouTrackingRecord.getFooterViewsCount() != 0) {
				lvDaLeTouTrackingRecord.removeFooterView(linearNoMore);
			}
			groupCount = 0;
			childCount = 0;
			pageno = 1;
			isRunning = true;
			isNoMoreRecord = true;
			isRefreshOrBottom = true;
			getTrackingRecordThread();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		super.onResume();
		isShow = true;
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
		if (UserInfo.getUserInfo().isRebuy()) {
			getParent().finish();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/* 显示提示框* */
	public void showNoMoreRecordDialog(String strMsg) {
		if (isShow) {
			ViewerUtil.showTipDialog(TrackingRecordDaLeTouAct.this, strMsg, false);
		}
	}

	/* 处理显示服务器获取信息* */
	public void infoHandling(ArrayList<TrackingRecordInfo> list) {
		ArrayList<Hashtable<String, String>> listTemp = new ArrayList<Hashtable<String, String>>();
		for (int i = 0; i < list.size(); i++) {
			Hashtable<String, String> map = new Hashtable<String, String>();
			String[] strAddTime = list.get(i).getAddDate().split(" ");
			map.put(Key.KEY_DATE, strAddTime[0]);
			map.put(Key.KEY_TIME, strAddTime[1]);
			map.put(Key.KEY_TOTALMONEY, moneyFormat(list.get(i).getAllMoney()));
			map.put(Key.KEY_FINISHNUM, list.get(i).getFinishTrackingNum());
			map.put(Key.KEY_PID, list.get(i).getID());
			map.put(Key.KEY_LOTID, list.get(i).getLotID());
			map.put(Key.KEY_STATE, list.get(i).getState());
			map.put(Key.KEY_PLAYNAME, list.get(i).getPlayTypeName());
			map.put(Key.KEY_TOTALNUM, list.get(i).getTotalTrackingNum());
			map.put(Key.KEY_LOTNAME, lotIDTransform(list.get(i).getLotID()));

			listTemp.add(map);
		}

		if (isRefreshOrBottom) {
			alItem.clear();
			alItem.addAll(listTemp);
			adapter.notifyDataSetChanged();
		} else {
			alItem.addAll(listTemp);
			adapter.notifyDataSetChanged();
		}
	}

	public String moneyFormat(String str) {
		double userRestTemp = Double.parseDouble(str);
		DecimalFormat format = new DecimalFormat("0.00");
		String afterBet = format.format(userRestTemp);
		return afterBet;
	}

	// 判断彩种
	public String lotIDTransform(String str) {
		String strShow = null;
		if (str.equals(Config.SHUANGSEQIU)) {
			strShow = "双色球";
		} else if (str.equals(Config.DALETOU)) {
			strShow = "大乐透";
		} else if (str.equals("7")) {
			strShow = "福彩3D";
		} else if (str.equals("11")) {
			strShow = "七乐彩";
		} else if (str.equals("4")) {
			strShow = "七星彩";
		} else if (str.equals("8")) {
			strShow = "22选5";
		} else if (str.equals("5")) {
			strShow = "排列三";
		} else if (str.equals("10001")) {
			strShow = "排列五";
		}

		return strShow;
	}

	private int groupCount = 0;
	private int childCount = 0;

	private void lengthAutoAdapter() {
		adapter.countCalculate();
		groupCount = adapter.getGroupCount();
		childCount = adapter.getChildCount();

		int itemHeight = (31 + 70) * groupCount + childCount * 70;
		EDebug.o(this, groupCount + "===" + childCount + "===" + itemHeight);
		EDebug.o(this, lvDaLeTouTrackingRecord.getHeight());
		// 判断是否需要加入额外item
		if (itemHeight < lvDaLeTouTrackingRecord.getHeight()) {
			LinearLayout linearChild = new LinearLayout(this);
			int bheight = 0;
			linearChild.setBackgroundColor(Color.WHITE);
			if (lvDaLeTouTrackingRecord.getFooterViewsCount() > 0) {
				bheight = lvDaLeTouTrackingRecord.getHeight() - itemHeight - 30;
			} else {
				bheight = lvDaLeTouTrackingRecord.getHeight() - itemHeight;
			}
			linearBottom.addView(linearChild);
			for (int i = 0; i < linearBottom.getChildCount(); i++) {
				linearBottom.getChildAt(i).getLayoutParams().height = bheight;
				linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
			}
			linearChild.setBackgroundColor(Color.WHITE);
			lvDaLeTouTrackingRecord.addFooterView(linearBottom);
		}
	}
}
